package com.blackhorse.topic;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.blackhorse.topic.Producer.*;

public class Consumer2 {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;

        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            //声明交换机：
            channel.exchangeDeclare(TOPIC_EXCHAGE, //交换机名称
                    BuiltinExchangeType.TOPIC //交换机类型，fanout、topic、direct、headers
            );
            //声明队列
            channel.queueDeclare(TOPIC_QUEUE_2, true, false, false, null);
            //队列绑定交换机，指定routing key
            channel.queueBind(TOPIC_QUEUE_2, TOPIC_EXCHAGE, "item.*");
            //创建消费者：并设置消息处理
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("路由key为：" + envelope.getRoutingKey());
                    System.out.println("交换机为：" + envelope.getExchange());
                    System.out.println("消息id为：" + envelope.getDeliveryTag());
                    System.out.println("消费者2-接收到的消息为：" + new String(body, "utf-8"));
                }
            };
            //监听消息
            channel.basicConsume(TOPIC_QUEUE_2, true, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }
}
